/*
 * Copyright (c) 2006-2021, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-12-10     xu       the first version
 */
#include "amap_location_api.h"

#define DBG_TAG "api.loc"
#define DBG_LVL DBG_LOG
#include <rtdbg.h>
#include <rtthread.h>
#include <string.h>

#include "cJSON.h"
#include "gbk2utf8.h"
#include "webclient.h"
#include "http_api_utils.h"
#include "sohu_wanip_api.h"

#define LOCATION_URL_FORMAT "http://restapi.amap.com/v3/ip?key=%s&ip=%s"
#define LOCATION_URL_BUFFER_MAX 128

amap_location_info_t amap_location_get()
{
    struct wanip_addr wanip = {0};
    if (wan_ip_address_get(&wanip) < 0) {
        LOG_E("get ip failed!");
        return RT_NULL;
    }

    char* url_buffer = rt_malloc(LOCATION_URL_BUFFER_MAX);
    if (url_buffer == RT_NULL) {
        LOG_E("alloc url buffer failed!");
        return RT_NULL;
    }

    rt_snprintf(url_buffer, LOCATION_URL_BUFFER_MAX, LOCATION_URL_FORMAT, APP_AMAP_API_KEY, wanip.ip);
    LOG_D("prepare location request URL done!");

    char* response = RT_NULL;
    size_t resp_len = 0;
    if (http_get(url_buffer, &response, &resp_len) < 0) {
        rt_free(url_buffer);
        LOG_E("webclient send get request failed.");
        return RT_NULL;
    }
    rt_free(url_buffer);
    LOG_D("response length: %d %d bytes", resp_len, strlen(response));

    amap_location_info_t loc_info = RT_NULL;
    if (resp_len > 0) {
        loc_info = rt_calloc(1, sizeof(struct location_info));
        if (loc_info == RT_NULL) {
            rt_free(url_buffer);
            web_free(response);
            LOG_E("alloc location info failed!");
            return RT_NULL;
        }

        cJSON* root = cJSON_Parse(response);
        parse_string_field(root, "province", &loc_info->province);
        parse_string_field(root, "city", &loc_info->city);
        parse_string_field(root, "adcode", &loc_info->adcode);
        parse_string_field(root, "rectangle", &loc_info->rectangle);
        cJSON_Delete(root);
    }

    if (response) {
        web_free(response);
    }
    return loc_info;
}

void amap_location_delete(amap_location_info_t loc)
{
    if (loc == RT_NULL) {
        LOG_E("loc null!");
        return;
    }

    SAFE_FREE(loc->province);
    SAFE_FREE(loc->city);
    SAFE_FREE(loc->adcode);
    SAFE_FREE(loc->rectangle);

    SAFE_FREE(loc);
}

static int loc_test(int argc, char* argv[])
{
    amap_location_info_t info = amap_location_get();
    RT_ASSERT(info);
    amap_location_delete(info);
    return 0;
}
MSH_CMD_EXPORT(loc_test, Location API test);
